<template>
  <div class="app-container">
    <avue-crud
      :option="option"
      ref="crud"
      :data="data"
      :table-loading="loading"
      :page.sync="page"
      @on-load="onLoad"
      @current-change="currentChange"
      @row-del="rowDel"
      @selection-change="selectionChange"
      @search-change="searchChange"
      @search-reset="resetChange"
    >
      <template
        slot="icon"
        slot-scope="scope"
      >
        <div v-if="scope.row.icon">
          <svg-icon :icon-class="scope.row.icon"></svg-icon>
        </div>
      </template>

      <template slot="menuLeft">
        <div style="display:inline-block;">
          <div style="display:flex">
            <el-upload
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-success="onSuccess"
              :on-error="onError"
              :headers="headers"
              :action="importCustomer"
            >
              <el-button
                type="primary"
                size="small"
                icon="el-icon-upload2"
                v-has="'authRecordsImport'"
              >
                {{importDataBtnText}}
              </el-button>
            </el-upload>
            <el-button
              size="small"
              type="primary"
              @click="downloadTemp"
              icon="el-icon-download"
              v-has="'authRecordsModelDownLoad'"
            >
              模板下载
            </el-button>
          </div>
        </div>

      </template>

      <template
        slot-scope="scope"
        slot="menu"
      >
        <el-button
          type="text"
          size="small"
          @click="handleGrant(scope.row)"
        > 查看</el-button>
      </template>
    </avue-crud>

    <el-dialog
      :title='title+`授权任务查看`'
      class="avue-dialog"
      center
      :visible.sync="box"
      width="80%"
    >
      <avue-crud
        :option="customerOption"
        :table-loading="customerLoading"
        :data="customerData"
        ref="customer_crud"
        @selection-change="customerSelectionChange"
        @size-change="sizeChange"
        :page.sync="customerPage"
        @current-change="customerChange"
        @search-change="customerSearchChange"
        @search-reset="customerResetChange"
      >
        <template slot="menuLeft">
          <el-button
            type="primary"
            icon="el-icon-download"
            size="small"
            :disabled="customerPage.total == 0"
            :loading="downLoading"
            @click.stop="handleDownload"
          >导出</el-button>
        </template>
      </avue-crud>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="cancel"
        >确 定</el-button>
        <!-- <el-button type="primary" v-if="handleType=='add'" @click="submit(handleType)">确 定</el-button>
                <el-button type="primary" v-if="handleType=='up'" @click="submit(handleType)">确 定</el-button> -->
      </span>
    </el-dialog>

    <el-dialog
      title="导入结果"
      :visible.sync="imptRestDialogVisible"
      width="45%"
    >
      <p
        v-for="o in imptRestInfo"
        :key="o"
        class=" text item"
        style="text-indent:30px"
      >
        {{ o }}
      </p>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="closeRestDialog"
        >关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getK,
  assignC,
  upAssign,
  celC,
  getCmpAuthRecords,
  getAuthRerd,
  downloadTemp,
} from '@/api/manager.js'
export default {
  data() {
    return {
      loading: false,
      form: {},
      /* 分页 */
      page: {
        pageSize: 10,

        pageSizes: [10, 20, 30, 40, 50, 100],
        pagerCount: 5,
        layout: 'total, sizes, prev, pager, next, jumper',

        currentPage: 1,
        total: 0,
        background: false,
      },
      data: [],
      importCustomer: '',
      importDataBtnText: '导 入',
      importDataBtnIcon: 'el-icon-upload2',
      importDataDisabled: false,

      imptRestInfo: [],
      imptRestDialogVisible: false,

      selectionList: [],
      searchList: {},
      customerSearchList: {},
      title: '',
      option: {
        headerAlign: 'center',
        align: 'center',
        border: true,
        // index: true,
        // indexLabel: '序号',
        indexWidth: 100,
        card: true,
        defaultExpandAll: true,
        dialogDrag: false,
        labelWidth: 135,
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,

        columnBtn: false,
        refreshBtn: false,
        selectClearBtn: false,
        // searchBtn: true,
        // searchSpan: 9,
        searchShowBtn: false,

        // selection: true,
        searchLabelWidth: '25%',
        searchSpan: 6,
        searchMenuSpan: 4,
        column: [
          {
            label: '授权渠道',
            prop: 'companyAccountBank',
            display: false,
            search: true,
            type: 'select',
            dicData: [],
          },
          // {
          //     label: '授权企业(家)',
          //     prop: 'allTaskNum',
          //     display: false,
          //     search: false
          // },

          {
            label: '授权企业(家)',
            prop: 'authedTaskNum',
            display: false,
            search: false,
          },
          // {
          //     label: '已授权企业数',
          //     prop: 'authedTaskNum',
          //     display: false,
          //     search: true,
          //     type: 'select',
          //     dicData: [{
          //         label: '小微企业',
          //         value: '1'
          //     }, {
          //         label: '中型企业',
          //         value: '2'
          //     }, {
          //         label: '大型企业',
          //         value: '3'
          //     }, {
          //         label: '超大型企业',
          //         value: '4'
          //     }, {
          //         label: '个体工商户',
          //         value: '5'
          //     }]
          // },
          {
            label: '未授权企业数(家)',
            prop: 'unAuthTaskNum',
            display: false,
            search: false,
          },
          // {
          //     label: '企业综合评分',
          //     prop: 'score',
          //     display: false
          // },
        ],
        group: [
          {
            icon: 'el-icon-info',
            label: '企业信息',
            collapse: true,
            column: [
              {
                label: '企业名称',
                prop: 'qymc',
              },
              {
                label: '社会统一信用代码',
                prop: 'shtyxydm',
              },
              {
                label: '注册时间',
                prop: 'clrq',
              },
              {
                label: '注册资金',
                prop: 'zczb',
              },
              {
                label: '企业类型',
                prop: 'qylx',
                type: 'select',
                dicData: [
                  {
                    label: '小微企业',
                    value: '1',
                  },
                  {
                    label: '中型企业',
                    value: '2',
                  },
                  {
                    label: '大型企业',
                    value: '3',
                  },
                  {
                    label: '超大型企业',
                    value: '4',
                  },
                  {
                    label: '个体工商户',
                    value: '5',
                  },
                ],
              },
              {
                label: '所属行业',
                prop: 'sshy',
                type: 'select',
                dicData: [
                  {
                    label: '请选择',
                    value: '',
                  },
                  {
                    label: '农林牧渔业',
                    value: '0',
                  },
                  {
                    label: '教育',
                    value: '1',
                  },
                  {
                    label: '采矿业',
                    value: '2',
                  },
                ],
              },
              {
                label: '注册地址',
                prop: 'zs',
                // }, {
                //     label: '企业性质',
                //     prop: 'qyxz',
              },
              {
                label: '企业联系方式',
                prop: 'dh',
              },
              {
                label: '企业综合评分',
                prop: 'score',
              },
            ],
          },
          {
            icon: 'el-icon-info',
            label: '法人信息',
            collapse: true,
            column: [
              {
                label: '法人姓名',
                prop: 'fddbr',
              },
              {
                label: '性别',
                prop: 'xb',
                type: 'select',
                dicData: [
                  {
                    label: '男',
                    value: '1',
                  },
                  {
                    label: '女',
                    value: '0',
                  },
                ],
              },
              {
                label: '出生日期',
                // type: 'csrq',
                prop: 'csrq',
              },
              {
                label: '籍贯',
                prop: 'jg',
              },
              {
                label: '婚姻状况',
                prop: 'hyzk',
                type: 'select',
                dicData: [
                  {
                    label: '已婚',
                    value: '1',
                  },
                  {
                    label: '未婚',
                    value: '0',
                  },
                ],
              },
              {
                label: '学历',
                prop: 'xl',
                type: 'select',
                dicData: [
                  {
                    label: '请选择',
                    value: '',
                  },
                  {
                    label: '专科',
                    value: '0',
                  },
                  {
                    label: '本科',
                    value: '1',
                  },
                  {
                    label: '其他',
                    value: '2',
                  },
                ],
              },

              {
                label: '身份证',
                prop: 'sfzjhm',
              },
              {
                label: '手机号',
                prop: 'lxdh',
              },
              {
                label: '邮箱',
                prop: 'yx',
              },
              {
                label: '联系地址',
                prop: 'dz',
              },
            ],
          },
        ],
      },

      /* 配置弹窗 */
      box: false,
      customerLoading: false,
      companyAccountBank: undefined,
      handleType: '',
      customerForm: {},
      downLoading: false,
      customerPage: {
        pageSize: 10,
        pageSizes: [10, 20, 30, 40, 50, 100],
        pagerCount: 5,
        layout: 'total, sizes, prev, pager, next, jumper',
        currentPage: 1,
        total: 0,
        background: false,
      },
      /* 已选中 客户经理 */
      customerSelectionList: [],
      customerData: [],
      customerOption: {
        headerAlign: 'center',
        align: 'center',
        border: true,
        // index: true,
        // indexLabel: '序号',
        indexWidth: 100,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        menu: false,
        rowKey: 'shtyxydm',
        selection: true,
        reserveSelection: true,
        dialogDrag: false,
        excelBtn: false,
        columnBtn: false,
        refreshBtn: false,
        selectClearBtn: false,
        // searchBtn: true,
        // searchSpan: 9,
        searchShowBtn: false,
        searchSpan: 6,
        searchLabelWidth: '25%',
        searchMenuSpan: 4,
        column: [
          {
            label: '企业名称',
            prop: 'companyName',
          },
          {
            label: '统一社会信用代码',
            prop: 'shtyxydm',
          },
          {
            label: '是否授权',
            prop: 'authFlg',
            type: 'select',
            search: true,
            dicData: [
              {
                label: '是',
                value: '1',
              },
              {
                label: '否',
                value: '3',
              },
            ],
          },
          {
            label: '授权时间',
            prop: 'authTime',
          },
          {
            label: '日期范围',
            prop: 'daterange',
            type: 'daterange',
            format: 'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期',
            display: false,
            search: true,
            searchRange: true,
            hide: true,
          },
          // {
          //     label: '所属机构',
          //     prop: 'deptCode'
          // },
          // {
          //     label: '所属部门',
          //     prop: 'province'
          // }
        ],
      },
    }
  },
  computed: {
    headers() {
      return {
        TOKEN: this.$store.getters.token,
      }
    },
  },
  created() {
    this.getDict()
  },
  methods: {
    async getDict() {
      const dataSQQD = await this.$store.dispatch('asyncApi/getDict', {
        code: 'SQQD',
      })
      this.option.column[0].dicData = dataSQQD
    },
    onLoad(page, params = {}) {
      // if (page.layout) {
      //     Object.assign(params, {
      //         page: 1,
      //         size: 10,
      //     });
      // } else {
      //     Object.assign(params, page);
      // }

      let baseUrl2 = process.env.VUE_APP_BASE_API
      this.importCustomer = baseUrl2 + '/qyxx/authorize/import'

      this.downCustomerTmp = baseUrl2 + '/qyxx/authorize/downloadTemp'

      let searchList = this.searchList
      Object.assign(params, {
        ...searchList,
        pageNum: this.page.currentPage,
        pageSize: this.page.pageSize,
      })

      this.loading = true
      getAuthRerd(params).then((data) => {
        if (data.status) {
          this.loading = false
          this.data = data.data.records
          this.page.total = data.data.total
        }
      })
    },
    /* 清空 */
    resetChange() {
      this.searchList = {}
      this.page.currentPage = 1
      this.page.pageSize = 10
      this.onLoad()
    },
    /* 搜索筛选 */
    searchChange(params, done) {
      done()
      this.page.currentPage = 1
      this.page.pageSize = 10
      this.searchList = { ...params }
      this.onLoad()
    },
    /* 改变页码 */
    currentChange(currentPage) {
      this.page.currentPage = currentPage
    },
    customerChange(i) {
      this.customerPage.currentPage = i
      this.onCustomerLoad()
    },
    sizeChange(val) {
      this.customerPage.pageSize = val
      this.onCustomerLoad()
    },
    /* 选中客户回调 */
    selectionChange(list) {
      this.selectionList = list
    },
    /* 查看 */
    handleGrant(row) {
      this.title = row['$companyAccountBank']
      this.companyAccountBank = row.companyAccountBank
      this.customerSearchList = {}
      this.box = true
      //this.onCustomerLoad();
      this.$nextTick(() => {
        this.$refs['customer_crud'].searchReset()
      })
    },
    /* 用户 && 角色列表行点击row选中 */
    rowClick(row) {
      this.data.map((item) => {
        if (item.shtyxydm == row.shtyxydm) {
          this.$refs.crud.toggleSelection()
          this.$refs.crud.toggleSelection([item])
        }
      })
    },
    /* 删除 */
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        delOrg({
          id: row.id,
        }).then(() => {
          this.onLoad(this.page)
          this.$message({
            type: 'success',
            message: '操作成功!',
          })
        })
      })
    },

    /* 选中客户经理回调 */
    customerSelectionChange(list) {
      console.log(list)
      this.customerSelectionList = list
      /* if (list.length <= 1) {
                    this.customerSelectionList = list;
                } else {
                    this.$refs.cutomer_crud.toggleSelection();
                    this.$message.error("请选择单个角色分配!");
                } */
    },
    customerRowClick(row) {
      this.customerData.map((item) => {
        if (item.id == row.id) {
          this.$refs.customer_crud.toggleSelection()
          this.$refs.customer_crud.toggleSelection([item])
        }
      })
    },
    /* 获取列表 */
    onCustomerLoad(page, params = {}) {
      let customerSearchList = this.customerSearchList
      Object.assign(params, {
        ...customerSearchList,
        pageNum: this.customerPage.currentPage,
        pageSize: this.customerPage.pageSize,
      })
      this.customerLoading = true
      params.companyAccountBank = this.companyAccountBank
      getCmpAuthRecords(params).then((data) => {
        if (data.status) {
          this.customerLoading = false
          this.customerData = data.data.records
          this.customerPage.total = data.data.total
        }
      })
    },
    customerSearchChange(params, done) {
      done()
      this.customerPage.currentPage = 1
      this.customerPage.pageSize = 10
      if (params.daterange) {
        params.startTime = params.daterange[0]
        params.endTime = params.daterange[1]
      }
      params.daterange = []
      this.customerSearchList = { ...params }
      this.$nextTick(() => {
        this.$refs['customer_crud'].toggleSelection()
      })
      this.onCustomerLoad()
    },
    customerResetChange() {
      this.customerSearchList = {}
      this.customerPage.currentPage = 1
      this.customerPage.pageSize = 10
      this.$nextTick(() => {
        this.$refs['customer_crud'].toggleSelection()
      })
      this.onCustomerLoad()
    },
    handleDownload() {
      let opt = {
        title: this.title + '授权任务',
        column: [
          {
            label: '企业名称',
            prop: 'companyName',
          },
          {
            label: '统一社会信用代码',
            prop: 'shtyxydm',
          },
          {
            label: '是否授权',
            prop: 'authFlg',
            dicData: [
              {
                label: '是',
                value: '1',
              },
              {
                label: '否',
                value: '3',
              },
            ],
          },
          {
            label: '授权时间',
            prop: 'authTime',
          },
        ],
      }

      let list = this.customerSelectionList
      if (list.length > 0) {
        //导出选中项
        this.$confirm('是否导出当前选中项?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          this.$Export.excel({
            title: opt.title,
            columns: opt.column,
            data: list,
          })
        })
      } else {
        //导出全部
        this.$confirm('是否导出当前条件下所有项?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          let customerSearchList = this.customerSearchList
          let params = {
            ...customerSearchList,
            pageNum: 1,
            pageSize: this.customerPage.total,
            companyAccountBank: this.companyAccountBank,
          }
          this.downLoading = true
          getCmpAuthRecords(params).then((res) => {
            this.downLoading = false
            if (res.status) {
              this.$Export.excel({
                title: opt.title,
                columns: opt.column,
                data: res.data.records,
              })
            } else {
              this.$message.error(res.msg)
            }
          })
        })
      }
    },
    /* 取消 */
    cancel() {
      this.box = false
      this.$refs.crud.toggleSelection()
      this.$refs.customer_crud.toggleSelection()
    },
    /* 收回客户 */
    celCustomer(row) {
      this.$confirm('确定将收回客户?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        celC({
          shtyxydm: row.shtyxydm,
        }).then((data) => {
          if (data.status) {
            this.onLoad(this.page)
            this.$message({
              type: 'success',
              message: '操作成功!',
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },

    closeRestDialog() {
      this.imptRestDialogVisible = false
      this.onLoad(this.page)
    },
    beforeUpload(file) {
      var FileExt = file.name.replace(/.+\./, '')
      if (['xlsx'].indexOf(FileExt.toLowerCase()) === -1) {
        this.$message({
          type: 'warning',
          message: '请使用下载的模板，上传后缀名为xlsx的文件！',
        })
        return false
      }
      this.importDataBtnText = '正在导入'
      this.importDataBtnIcon = 'el-icon-loading'
      this.importDataDisabled = true
      this.imptRestInfo = []
    },
    onSuccess(response, file, fileList) {
      this.importDataBtnText = '导 入'
      this.importDataBtnIcon = 'el-icon-upload2'
      this.importDataDisabled = false
      // console.log(response)
      this.onLoad(this.page)

      this.imptRestDialogVisible = true
      if (response.status) {
        this.imptRestInfo = response.data
      } else {
        this.imptRestInfo.push(response.msg)
      }

      // this.$message({
      //     type: "success",
      //     message: "导入成功!"
      // });
      // this.initEmps();
    },
    onError(err, file, fileList) {
      this.importDataBtnText = '导 入'
      this.importDataBtnIcon = 'el-icon-upload2'
      this.importDataDisabled = false
      this.onLoad(this.page)
      this.$message({
        type: 'error',
        message: '导入失败!',
      })
    },

    downloadTemp() {
      //document.location.href = this.downCustomerTmp
      downloadTemp().then((res) => {
        let fileName = '授权任务模板.xlsx'
        var link = document.createElement('a')
        link.href = window.URL.createObjectURL(res)
        link.download = fileName
        link.click()
        //释放内存
        window.URL.revokeObjectURL(link.href)
      })
    },

    // exportExcel() {
    //     debugger
    //     this.$export.excel(this.customerOption);
    // },

    submit(e) {
      let form = []
      if (this.customerSelectionList.length === 0) {
        this.$message.warning('请选择至多一条数据')
        return
      } else if (this.customerSelectionList.length > 1) {
        this.$message.warning('请选择至多一条数据')
        return
      } else {
        // form = this.customerSelectionList;
        // let form = new Map();
        // form.set("eid",this.customerSelectionList[0].eid)
        var shtyxydms = []
        shtyxydms.push(this.selectionList[0].shtyxydm)
        // form.set("shtyxydms",shtyxydms)

        // form.eid = this.customerSelectionList[0].eid;

        if (e == 'up') {
          upAssign(
            this.selectionList[0].shtyxydm,
            this.customerSelectionList[0].eid
          ).then((data) => {
            if (data.status) {
              this.box = false
              this.$message.success(data.msg)
              this.customerSelectionList = []
              this.selectionList = []
              this.$refs.crud.toggleSelection()
              this.$refs.customer_crud.toggleSelection()
              this.onLoad(this.page)
            } else {
              this.$message.error(data.msg)
            }
          })
        } else {
          assignC({
            shtyxydms: shtyxydms,
            eid: this.customerSelectionList[0].eid,
          }).then((data) => {
            if (data.status) {
              this.box = false
              this.$message.success(data.msg)
              this.customerSelectionList = []
              this.selectionList = []
              this.$refs.crud.toggleSelection()
              this.$refs.customer_crud.toggleSelection()
              this.onLoad(this.page)
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      }
    },
  },
}
</script>

<style scoped="scoped" lang="scss">
/deep/ .avue-crud__pagination {
  text-align: center;
}
</style>
